﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ciripescu_WebRole.BL;
using Ciripescu_WebRole.Entities;
using System.Collections;
using Bitstar.YahooImport;
using Microsoft.Samples.ServiceHosting.StorageClient;


namespace Ciripescu_WebRole
{
    public partial class find : Page
    {
        protected void btnYahooImport_Click(object sender, EventArgs e)
        {
            YahooContactImport import = new YahooContactImport();
            string user = txtYahooUser.Text;
            string password = txtYahooPassword.Text;
            if (user.Contains("@")) user = (user.Split('@'))[0];
            MailContactList list = new MailContactList();
            if (user == "" || password == "")
            {
                errors.InnerHtml = "Intai completeaza userul si parola de yahoo!";
                return;
            }
            try
            {
                list = Utils.ValidateContactList(import.ExtractContacts(user, password), (string)Session["UserName"]);
            }
            catch (InvalidPassOrUsernameException)
            {
                errors.InnerHtml = "User sau parola gresita";
                return;
            }
            catch (UnexpectedResponseException ee)
            {
                errors.InnerHtml = "naspa de tot";
                return;
            }
            catch (Exception eee)
            {
                return;
            }
            Session["ContactList"] = list;
            //Response.Redirect("import.aspx");
            Response.Redirect("/import/");
        }
        //private void PopulateDataGrid()
        //{
        //    string userName = (string)Session["UserName"];
        //    UserManager um = new UserManager();
        //    UrmarireManager urmManag = new UrmarireManager();

        //    //List<User> allUsers      = um.GetAllItems().ToList<User>();
        //    //List<Urmarire> urmarire  = (urmManag.GetFollowedUsers(userName)).ToList<Urmarire>();

        //    List<User> notFollowed = urmManag.GetNotFollowedUsers(userName).ToList<User>();

        //    if (notFollowed.Count == 0)
        //    {
        //        btnCheckAll.Visible  = false;
        //        btnUncheck.Visible   = false;
        //        btnUrmareste.Visible = false;

        //        txtSearchInput.Text = "No user found";
        //    }
            
        //        gwNotFollowed.DataSource = notFollowed;
        //        gwNotFollowed.DataBind();
        //}

        protected void Page_Load(object sender, EventArgs e)
        {
            // pune buttonul pe default submit
            txtYahooPassword.Attributes.Add("onkeypress", "return clickButton(event,'" + btnYahooImport.ClientID + "')");
            //if (!IsPostBack)
            //{
            //    PopulateDataGrid();
            //}
        }

        //protected void btnUrmareste_Click(object sender, EventArgs e)
        //{
        //    UrmarireManager urmManag = new UrmarireManager();
        //    UserManager um = new UserManager();
        //    List<User> notFollowed = urmManag.GetNotFollowedUsers((string)Session["UserName"]).ToList<User>();

        //    if (gwNotFollowed.Rows.Count != notFollowed.Count)
        //    {
        //        gwNotFollowed.DataSource = notFollowed;
        //        gwNotFollowed.DataBind();
        //    }

        //    for (int i = 0; i < gwNotFollowed.Rows.Count; i++)
        //    {
        //        GridViewRow row = gwNotFollowed.Rows[i];
        //        bool isChecked = ((CheckBox)row.FindControl("chkMarked")).Checked;

        //        if (isChecked)
        //        {
        //            User whoFollows = um.GetItem((string)Session["UserName"]);
        //            Urmarire u = new Urmarire(whoFollows.PartitionKey,
        //                                      notFollowed[i].PartitionKey);
        //            urmManag.Insert(u);
        //            MailQueue mq = new MailQueue();
        //            mq.SendNewUrmaritorNotification(notFollowed[i].FullName,
        //                                            notFollowed[i].Email,
        //                                            whoFollows.FullName,
        //                                            whoFollows.Email,
        //                                            notFollowed[i].GetUserName(),
        //                                            whoFollows.GetUserName());
        //        }
        //    }
        //    PopulateDataGrid();
        //}

        //protected void btnCheckAll_Click(object sender, EventArgs e)
        //{
        //    for (int i = 0; i < gwNotFollowed.Rows.Count; i++)
        //    {
        //        GridViewRow row = gwNotFollowed.Rows[i];
        //        ((CheckBox)row.FindControl("chkMarked")).Checked = true;
        //    }
        //}

        //protected void btnUncheck_Click(object sender, EventArgs e)
        //{
        //    for (int i = 0; i < gwNotFollowed.Rows.Count; i++)
        //    {
        //        GridViewRow row = gwNotFollowed.Rows[i];
        //        ((CheckBox)row.FindControl("chkMarked")).Checked = false;
        //    }
        //}

        //protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
        //{
        //    for (int i = 0; i < gwNotFollowed.Rows.Count; i++)
        //    {
        //        GridViewRow row = gwNotFollowed.Rows[i];
        //        ((CheckBox)row.FindControl("chkMarked")).Checked = false;
        //    }
        //}

        protected void btnFollow_OnClick(object sender, EventArgs e)
        {
            ImageButton lb         = (ImageButton)sender;
            string toFollowUn = lb.CommandArgument;

            UserManager uManag       = new UserManager();
            User toFollow            = uManag.GetItem(toFollowUn);
            User whoFollows          = uManag.GetItem((string)Session["UserName"]);
            Urmarire urm             = new Urmarire(whoFollows.GetUserName(), toFollow.GetUserName());
            UrmarireManager urmManag = new UrmarireManager();
            urmManag.Insert(urm);

            MailQueue mq = new MailQueue();
            mq.SendNewUrmaritorNotification(toFollow.FullName,
                                            toFollow.Email,
                                            whoFollows.FullName,
                                            whoFollows.Email,
                                            toFollow.PartitionKey,
                                            whoFollows.PartitionKey);
            lb.Visible          = false;
            lb.ImageUrl = "/images/buttons/urmarit.png";
            lb.Enabled  = false;
            //Label lblFollowed   = (Label)Repeater1.Items[0].FindControl("lblAlreadyFollowed");
            //lblFollowed.Visible = true;
        }
        
        protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            User usr = (User)e.Item.DataItem;
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;

            UserManager uManag = new UserManager();
            ImageButton btnFollow   = (ImageButton)e.Item.FindControl("btnFollow");
            Label lblFollowed  = (Label)e.Item.FindControl("lblAlreadyFollowed");

            if (uManag.Follows((string)Session["UserName"], usr.GetUserName()))
            {
                btnFollow.Visible   = false;
                lblFollowed.Visible = true;
            }
            else
            {
                btnFollow.Visible   = true;
                lblFollowed.Visible = false;
            }
        }

        protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            ImageButton b = (ImageButton)e.CommandSource;

            UrmarireManager urmManag = new UrmarireManager();
            Urmarire urm = new Urmarire((string)Session["UserName"], b.CommandArgument);
            urmManag.Insert(urm);

            Label lblFollowed = (Label)e.Item.FindControl("lblAlreadyFollowed");
            lblFollowed.Visible = true;
            b.Visible = b.Enabled = false;
        }

        protected void btnCauta_Click(object sender, EventArgs e)
        {
            string usrToFind  = txtSearchInput.Text;

            UserManager uManag       = new UserManager();             
            List<User> list          = uManag.Search(usrToFind);
            
            int index = -1;
            if (list.Count != 0)
            {
                foreach (User usr in list)
                    if (usr.PartitionKey.CompareTo((string)Session["UserName"]) == 0)
                        index = list.IndexOf(usr);
                if(index >= 0)
                  list.RemoveAt(index);
            }

            Repeater1.DataSource     = list;
            Repeater1.DataBind();
        }

        protected void Wizard2_Load(object sender, EventArgs e)
        {

        }


        //private void YahooImport()
        //{
        //    if (!Page.IsValid)
        //        return;

        //    YahooContactImport import = new YahooContactImport();

        //    string user = txtUserName.Text;
        //    string password = txtPassword.Text;

        //    if (user.Contains("@")) user = (user.Split('@'))[0];

        //    MailContactList list = new MailContactList();
        //    try
        //    {
        //        list = import.ExtractContacts(user, password);
        //    }
        //    catch (InvalidPassOrUsernameException ex)
        //    {
        //        Utils.WriteLog(EventLogName.Warning, ex.ToString());
        //        divError.InnerHtml = Properties.Resources.ErrInvalidLogin;
        //        return;
        //    }
        //    catch (UnexpectedResponseException ex)
        //    {
        //        Utils.WriteLog(EventLogName.Warning, ex.ToString());
        //        divError.InnerHtml = Properties.Resources.ErrInvalidLogin;
        //        return;
        //    }
        //    catch (Exception ex)
        //    {
        //        Utils.WriteLog(EventLogName.Warning, ex.ToString());
        //        divError.InnerHtml = Properties.Resources.ErrInvalidLogin;
        //        return;
        //    }

        //    UserManager uManag = new UserManager();
        //    UrmarireManager urmManag = new UrmarireManager();

        //    List<MailContact> sendInvitationsList = new List<MailContact>();
        //    List<User> inviteToFollow = new List<User>();
        //    if (list != null)
        //    {
        //        foreach (MailContact mc in list)
        //        {
        //            User currUser = uManag.GetItemByEmail(mc.Email);
        //            if (currUser == null)
        //                sendInvitationsList.Add(mc);
        //            else
        //                if (uManag.Follows((string)Session["UserName"], currUser.PartitionKey) == false)
        //                    inviteToFollow.Add(currUser);
        //        }
        //    }

        //    Session.Add("InvitationList", sendInvitationsList);
        //    Session.Add("ToFollowList", inviteToFollow);
        //    if (inviteToFollow.Count == 0)
        //    {
        //        Wizard1.ActiveStepIndex = 2; //directly to sending invites
        //        lblInfo.Text = "Trimit invitatii la cei selectati...";
        //        gwToFollowNotOnCirip.DataSource = sendInvitationsList;
        //        gwToFollowNotOnCirip.DataBind();
        //    }
        //    else
        //    {
        //        lblInfo.Text = "Vreau sa ii urmaresc pe cei selectati...";
        //        gwToFollowOnCiripescu.DataSource = inviteToFollow;
        //        gwToFollowOnCiripescu.DataBind();
        //    }
        //}

        //private void GoogleImport()
        //{
        //    throw new Exception("TODO");

        //}

        //private void FollowSelectedUsers()
        //{
        //    if (!Page.IsValid)
        //        return;

        //    List<User> list = (List<User>)Session["ToFollowList"];
        //    UrmarireManager um = new UrmarireManager();
        //    for (int i = 0; i < gwToFollowOnCiripescu.Rows.Count; i++)
        //    {
        //        GridViewRow row = gwToFollowOnCiripescu.Rows[i];
        //        if (((CheckBox)row.FindControl("chkMarked")).Checked == true)
        //        {
        //            //list[i] - cel pe care il urmaresc, eu, userul curent - currUser
        //            User currUser = (new UserManager()).GetItem((string)Session["UserName"]);
        //            um.Insert(new Urmarire(currUser.PartitionKey, list[i].PartitionKey));

        //            MailQueue mq = new MailQueue();
        //            mq.SendNewUrmaritorNotification(list[i].FullName,
        //                                            list[i].Email,
        //                                            currUser.FullName,
        //                                            currUser.Email,
        //                                            list[i].PartitionKey,
        //                                            currUser.PartitionKey);
        //        }
        //    }
        //    //bind grid for the invitations view
        //    gwToFollowNotOnCirip.DataSource = (List<MailContact>)Session["InvitationList"];
        //    gwToFollowNotOnCirip.DataBind();
        //}

        //private void SendInvitations()
        //{
        //    MailQueue mailQueue = new MailQueue();

        //    List<MailContact> mailToList = (List < MailContact >)Session["InvitationList"];
        //    if(mailToList.Count != gwToFollowNotOnCirip.Rows.Count)
        //    {
        //        gwToFollowNotOnCirip.DataSource = mailToList;
        //        gwToFollowNotOnCirip.DataBind();
        //    }

        //    User curUser = (new UserManager()).GetItem((string)Session["UserName"]);
        //    for (int i=0; i < gwToFollowNotOnCirip.Rows.Count; i++)
        //    {
        //        GridViewRow row = gwToFollowNotOnCirip.Rows[i];
        //        if (((CheckBox)row.FindControl("chkMarked")).Checked == true)
        //            mailQueue.SendInvitation(mailToList[i].Name,mailToList[i].Email,curUser.FullName,curUser.Email);
                    
        //    }
        //    //Response.Redirect("~/home.aspx?userId=" + (string)Session["UserName"]);
        //    Response.Redirect("/home/");
        //}

        //protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
        //{
        //    if (Wizard1.ActiveStepIndex == 0)
        //    {
        //        switch (radEmailProvider.SelectedIndex)
        //        {
        //            case 0:
        //                YahooImport();
        //                break;
        //            case 1:
        //                GoogleImport();
        //                break;
        //            default:
        //                YahooImport();
        //                break;
        //        }
        //    }
        //    if (Wizard1.ActiveStepIndex == 1)
        //    {
        //        FollowSelectedUsers();
        //    }
        //}

        //protected void OnActivate_WizardStep2(object sender, EventArgs e)
        //{
        //    //imgLoading.Visible = false;
        //}

        //protected void Wizard1_ActiveStepChanged(object sender, EventArgs e)
        //{
        //    ArrayList steps = (ArrayList)Wizard1.GetHistory();
        //    if (steps.Count == 0) return;
        //    WizardStepBase last_step = (WizardStepBase)steps[0];
            
        //    if (Wizard1.WizardSteps.IndexOf(last_step) == 0) //un-pass
        //    {
                
        //    }

        //    if (Wizard1.WizardSteps.IndexOf(last_step) == 1) //follow
        //    {
        //        //FollowSelectedUsers();
        //    }
                
        //    if (Wizard1.WizardSteps.IndexOf(last_step) == 2) //send invites
        //    {
        //        //SendInvitations();
        //    }
        //}
                
        //protected void gwToFollowNotOnCirip_PageIndexChanged(object sender, EventArgs e)
        //{
           
        //}

        //protected void gwToFollowNotOnCirip_PageIndexChanging(object sender, GridViewPageEventArgs e)
        //{
        //    gwToFollowNotOnCirip.PageIndex = e.NewPageIndex;
        //    gwToFollowNotOnCirip.DataSource = (List < MailContact >)Session["InvitationList"];
        //    gwToFollowNotOnCirip.DataBind();
        //}

        //protected void chkSelect1_OnClickChanged(object sender, EventArgs e)
        //{
        //    for (int i=0; i < gwToFollowOnCiripescu.Rows.Count; i++)
        //    {
        //        GridViewRow row = gwToFollowOnCiripescu.Rows[i];
        //        ((CheckBox)row.FindControl("chkMarked")).Checked = ((CheckBox)gwToFollowOnCiripescu.HeaderRow.FindControl("chkSelect1")).Checked;
        //    }
        //}

        //protected void chkSelect2_OnClickChanged(object sender, EventArgs e)
        //{
        //    for (int i=0; i < gwToFollowNotOnCirip.Rows.Count; i++)
        //    {
        //        GridViewRow row = gwToFollowNotOnCirip.Rows[i];
        //        ((CheckBox)row.FindControl("chkMarked")).Checked = ((CheckBox)gwToFollowNotOnCirip.HeaderRow.FindControl("chkSelect2")).Checked;
        //    }
        //}

        protected void btnSendInvitations_Click(object sender, EventArgs e)
        {
            MailQueue mq = new MailQueue();
            
            if(txtAddresses.Text != String.Empty)
            {
                string [] split   = txtAddresses.Text.Split(',');
                txtAddresses.Text = String.Empty;
                int i = 0;
                User curUsr = (new UserManager()).GetItem((string)Session["UserName"]);
                
                try
                {
                    if (split[i].Contains('@') && split[i].Contains('.'))
                    {
                        mq.SendInvitation(split[i], split[i], curUsr.FullName, curUsr.Email);
                        InviteManager im = new InviteManager();
                        ///put invitation in invite
                        Invite inv = im.GetItem(split[i]);
                        if (inv == null)
                        {
                            inv = new Invite(split[i], split[i], 0, DateTime.Now);
                            im.Insert(inv);
                        }
                    }
                    i++;
                }
                catch (Exception)
                {
                }

                //Response.Redirect("~/home.aspx");
                Response.Redirect("/home/");
            }
        }

        //protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
        //{
        //    //Response.Redirect("~/home.aspx?userId=" +  (string)Session["UserName"]);
        //    //SendInvitations();
        //    Response.Redirect("/home/");
        //}

        protected void btnSendYahooInvitations_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("/invita/");
        }
    }
}
